package com.thememaker.util;

import com.thememake.entity.ThemeFileInfo;
import com.thememake.ui.dialog.ProgressDialog;
import com.thememake.util.xml.fontcolor.ReadXmlUtils;
import com.thememaker.lockstyle.LockstylePaserUtils;
import com.thememaker.lockstyle.bean.Lockscreen;
import com.thememaker.lockstyle.bean.command.BaseCommand;
import com.thememaker.lockstyle.bean.command.IntentCommand;
import com.thememaker.lockstyle.bean.command.Trigger;
import com.thememaker.lockstyle.bean.ui.BaseView;
import com.thememaker.lockstyle.bean.ui.Button;
import com.thememaker.lockstyle.bean.ui.Group;
import com.thememaker.lockstyle.bean.ui.Image;
import javafx.stage.Stage;
import org.w3c.dom.Document;

import java.io.File;
import java.util.LinkedHashMap;
import java.util.Optional;
import java.util.function.Consumer;

/**
 * @author yiyi.zheng 2018/9/20
 */
public class CheckManifestUtils {
    private static CheckManifestUtils checkManifestUtils;
    private Document document;
    private Lockscreen lockscreen;
    private LinkedHashMap<String, BaseView> map;

    private static final String IMAGE_NAME = "bg";
    private static final String IMAGE_SRC = "default_lock_wallpaper_2400.jpg";

    private static final String GROUP_TIME = "time_grp";
    private static final String GROUP_INTENT = "intent_grp";
    private static final String GROUP_BUTTON = "img_btn_grp";

    private LinkedHashMap<String, Image> bgImageMap = new LinkedHashMap<>();
    private LinkedHashMap<String, Image> imageGroupMap = new LinkedHashMap<>();
    private LinkedHashMap<String, Group> timeGroupMap = new LinkedHashMap<>();
    private LinkedHashMap<String, Group> intentGroupMap = new LinkedHashMap<>();

    public static CheckManifestUtils getInstance() {
        if (checkManifestUtils == null) {
            checkManifestUtils = new CheckManifestUtils();
        }
        return checkManifestUtils;
    }

    public boolean checkUnlockRuleProgress(ThemeFileInfo themeFileInfo, String themeType, Stage primaryStage, Consumer<String> consumer) {
        ProgressDialog progressFrom = new ProgressDialog(primaryStage, "正在检测...");
        progressFrom.showProgressBar();
        System.out.println("检测开始时间 >>> " + System.currentTimeMillis());
        if (checkUnlockRule(themeFileInfo, themeType, consumer)) {
            progressFrom.cancelProgressBar();
            System.out.println("检测结束时间 >>> " + System.currentTimeMillis());
            return true;
        } else {
            progressFrom.cancelProgressBar();
            System.out.println("检测结束时间 >>> " + System.currentTimeMillis());
            return false;
        }
    }

    public boolean checkUnlockRule(ThemeFileInfo themeFileInfo, String themeType, Consumer<String> consumer) {
        String xmlPath = themeFileInfo.getThemeDir() + File.separator + themeType + File.separator + ThemeFileInfo.LOCKSTYLE_NAME + File.separator + ThemeFileInfo.LOCKSCREEN_NAME + File.separator + "manifest.xml";
        document = ReadXmlUtils.loadXml(xmlPath);
        lockscreen = LockstylePaserUtils.paserLockScreenXml(document);
        map = lockscreen.getLockScreenViewMap();
        classifyBaseView();
        if (bgImageMap.isEmpty()) {
            consumer.accept("没有找到壁纸相对应的Image组件");
            return true;
        }
        if (checkImageNode(consumer)) {
            return true;
        }
        if (checkTimeNode()) {
            consumer.accept("没有找到时间相对应的Group组件");
            return true;
        }
        if (checkIntentNode(consumer)) {
            return true;
        }
        return false;
    }

    private void classifyBaseView() {
        map.keySet().forEach(key -> {
            BaseView baseView = map.get(key);
            if (baseView instanceof Group) {
                Group group = (Group) baseView;
                String name = Optional.ofNullable(group.getName()).orElse("");
                if (name.contains(GROUP_TIME)) {
                    timeGroupMap.put(group.getId(), group);
                } else if (name.contains(GROUP_INTENT)) {
                    intentGroupMap.put(group.getId(), group);
                }
            } else if (baseView instanceof Image) {
                Image image = (Image) baseView;
                String name = Optional.ofNullable(image.getName()).orElse("");
                String src = Optional.ofNullable(image.getSrc()).orElse("");
                if (src.equals(IMAGE_SRC) && name.equals(IMAGE_NAME)) {
                    bgImageMap.put(image.getId(), image);
                } else {
                    imageGroupMap.put(image.getId(), image);
                }
            }
        });
    }

    private boolean checkImageNode(Consumer<String> consumer) {
        if (imageGroupMap != null && !imageGroupMap.isEmpty()) {
            for (String key : imageGroupMap.keySet()) {
                Image image = imageGroupMap.get(key);
                if (judgeImageNode(image, consumer, "")) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean judgeImageNode(Image image, Consumer<String> consumer, String tips) {
        if (image.getSourcesAnimation() == null) {
            if (image.getName() == null) {
                consumer.accept(tips + "Image组件有不存在Name的");
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    private boolean checkTimeNode() {
        if (timeGroupMap != null && !timeGroupMap.isEmpty()) {
            return false;
        }
        return true;
    }

    private boolean checkIntentNode(Consumer<String> consumer) {
        if (intentGroupMap != null && !intentGroupMap.isEmpty()) {
            for (String key : intentGroupMap.keySet()) {
                Group group = intentGroupMap.get(key);
                LinkedHashMap<String, BaseView> groupMap = group.getGroupViewMap();
                LinkedHashMap<String, Image> groupImageMap = getGroupImage(groupMap);
                LinkedHashMap<String, Button> groupButtonMap = getGroupButton(groupMap);
                if (judgeIntentButton(groupImageMap, groupButtonMap, consumer)) {
                    return true;
                }
            }
        }
        return false;
    }

    private LinkedHashMap<String, Image> getGroupImage(LinkedHashMap<String, BaseView> groupMap) {
        LinkedHashMap<String, Image> groupImageMap = new LinkedHashMap<>();
        groupMap.keySet().forEach(key -> {
            if (groupMap.get(key) instanceof Image) {
                groupImageMap.put(groupMap.get(key).getId(), (Image) groupMap.get(key));
            }
        });
        return groupImageMap;
    }

    private LinkedHashMap<String, Button> getGroupButton(LinkedHashMap<String, BaseView> groupMap) {
        LinkedHashMap<String, Button> groupButtonMap = new LinkedHashMap<>();
        groupMap.keySet().forEach(key -> {
            if (groupMap.get(key) instanceof Button) {
                groupButtonMap.put(groupMap.get(key).getId(), (Button) groupMap.get(key));
            }
        });
        return groupButtonMap;
    }

    //xuyouhua
    private boolean judgeIntentButton(LinkedHashMap<String, Image> groupImageMap, LinkedHashMap<String, Button> groupButtonMap, Consumer<String> consumer) {
        for (String buttonKey : groupButtonMap.keySet()) {
            Button button = groupButtonMap.get(buttonKey);
            for (String triggerKey : button.getTriggers().getTriggerMap().keySet()) {
                Trigger trigger = button.getTriggers().getTriggerMap().get(triggerKey);
                for (String commandKey : trigger.getCommandMap().keySet()) {
                    BaseCommand baseCommand = trigger.getCommandMap().get(commandKey);
                    if (baseCommand instanceof IntentCommand) {
                        boolean tag = true;
                        for (String imageKey : groupImageMap.keySet()) {
                            Image image = groupImageMap.get(imageKey);
                            if (judgeImageNode(image, consumer, "快捷Group中")) {
                                return true;
                            }
                            if (button.getName().contains(image.getName())) {
                                tag = false;
                            }
                        }
                        if (tag) {
                            consumer.accept("没有找到快捷相对应的Image组件");
                        }
                        return tag;
                    }
                }
            }
        }
        return false;
    }
}
